#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import cgi, os, re, string, random
import cgitb

FILES_DIR_URL = "https://yourdomainhere/simple-fileshare/files"

cgitb.enable(display=0, logdir=".")

form = cgi.FieldStorage()

filename = ''
fullFilename = ''
filenameOutput = ''
copyButton = ''
try:
    # A nested FieldStorage instance holds the file
    fileitem = form['file']

    # Test if the file was uploaded
    if fileitem.filename:

        filetype = os.path.basename(fileitem.filename).split('.')[-1]
        if filetype: # sanitize
            filetype = ''.join(re.findall('[a-zA-Z0-9]',filetype))
            # Generate a random 16 char filename, to avoid directory traversal and whatnot
            filename = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(16)) + f".{filetype}"
            open(f"files/{filename}", 'wb').write(fileitem.file.read())

        if filename:
            fullFilename = f"{FILES_DIR_URL}/{filename}"
            filenameOutput = f"<p><input type='text' value='{fullFilename}' readonly style='width: 100%'></p>"
            copyButton = "<button onclick=\"copyLinkToClipboard()\">Copy link</button>"
except:
    # We don't really want to do anything here...
    someVar = 0


print("""Content-Type: text/html

<!DOCTYPE html>
<html>
    <head>
        <title>Simple Filesharing</title>
		<style>
			body {
				max-width: 45em; margin: auto; padding: 0 1em 5em; background-color: #333333; color: #dddddd;
			}
		</style>
        <script>
            function copyLinkToClipboard() {
                try {
                    navigator.clipboard.writeText("%s");
                    document.getElementById("output").innerHTML = "Link copied to clipboard";
                } catch (error) {
                    console.error(error);
                }
            }
        </script>
		<meta charset='utf-8'>
		<meta name='viewport' content='width=device-width,initial-scale=1'>
    </head> 
    <body>
        <form enctype="multipart/form-data" action="index.cgi" method="post">
            <p>File: <input type="file" name="file"><input type="submit" value="Upload"></p>
            %s
        </form>
            %s
            <p id="output"><p>
    </body>
</html>
""" % (fullFilename,filenameOutput,copyButton))
